﻿using GalaSoft.MvvmLight.Threading;
using Glorysoft.Auto.Xfw;
using Glorysoft.EAP.Core;
using Glorysoft.EAP.Core.Enums;
using Glorysoft.EAP.EAPClient.Common;
using Glorysoft.EAP.EAPClient.Model;
using Glorysoft.EAP.EAPClient.ViewModel;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using Serilog.Core;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
using System.Windows;
using System.Xml;

namespace Glorysoft.EAP.EAPClient
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static Logger ServiceLogger;
        private Mutex mutx;
        /// <summary>
        /// 程序入口
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            bool bNewCreate;
            mutx = new Mutex(true, "SMECEAP2Client", out bNewCreate);
            if (!bNewCreate)
            {
                CMessageBox.Show("EAPClient already start！", "系统提示", CMessageBoxButton.OK, CMessageBoxImage.Warning);
                Environment.Exit(0);
            }
            Initial();
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            System.Environment.Exit(0);
        }

        public static RunService ClientService = RunService.Current;
        /// <summary>
        /// 程序初始化
        /// </summary>
        private void Initial()
        {
            try
            {
                //初始化配置文件及日志文件
                IConfiguration config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile("barcode.json", true, true)
                .Build();
                var xfw = XfwContext.Current;
                XfwContext.Configuration = config;
                ServiceLogger = XfwContext.EapLogger;
                ReadJson();
                var proberid = config.GetSection("ProbeId").Get<string>();
                var testerid = config.GetSection("TesterId").Get<string>();
                var FacilityId = config.GetSection("FacilityId").Get<string>();
                var NeedleMaterialType1 = config.GetSection("NeedleMaterialGold").Get<string>();//获取金针信息
                var NeedleMaterialType2 = config.GetSection("NeedleMaterialRheniumtungsten").Get<string>();//获取铼钨针信息
                var specialRecipeName = config.GetSection("WATSpecialRecipeName").Get<string>();//获取WAT 特殊选片的recipe name
                Dict.Current.SpecialRecipeName = specialRecipeName;                              
                EqpClientInfo entity = new EqpClientInfo(proberid);
                entity.TesterName = testerid;
                entity.ProberName = proberid;
                entity.FacilityId = FacilityId;
                entity.NeedleMaterialType1 = NeedleMaterialType1;
                entity.NeedleMaterialType2 = NeedleMaterialType2;               
                entity.ConnStatus = false;
                entity.ProberStatus = false;
                entity.TesterStatus = false;
                entity.EQPConnStatus = false;
                if (Dict.Current.EAPName == "EAPServer" || Dict.Current.EAPName == "EAPServer_OCR")
                {   //type1 FP3000
                    entity.Lab_Probercard = Visibility.Visible;
                    entity.Txt_ProberCardID = Visibility.Visible;
                    entity.Lab_Alignment = Visibility.Visible;
                    entity.Lab_CheckZH = Visibility.Visible;
                    entity.AlignmentYes = Visibility.Visible;
                    entity.AlignmentNo = Visibility.Visible;
                    entity.CheckZHYes = Visibility.Visible;
                    entity.CheckZHNo = Visibility.Visible;
                    entity.Lbl_chipselecttype1 = Visibility.Visible;
                    // entity.AutoSelectWaferTesttype1 = Visibility.Visible;
                    // entity.ManualSelectWaferTesttype1 = Visibility.Visible;
                    entity.TestMode = Visibility.Visible;
                }
                else if (Dict.Current.EAPName == "EAPTelKeysight" || Dict.Current.EAPName == "EAPTelKeysight2")
                {
                    //type2  AYWAT
                    entity.Lbl_chipselecttype2 = Visibility.Visible;
                    entity.AutoSelectWaferTesttype2 = Visibility.Visible;
                    entity.ManualSelectWaferTesttype2 = Visibility.Visible;
                    //entity.TestMode = Visibility.Visible;
                }
                else
                {
                    //type3 BYWAT  amida liandong
                    entity.Lab_Probercard = Visibility.Visible;
                    entity.Txt_ProberCardID = Visibility.Visible;
                    entity.Lbl_chipselecttype3 = Visibility.Visible;
                    entity.AutoSelectWaferTesttype3 = Visibility.Visible;
                    entity.ManualSelectWaferTesttype3 = Visibility.Visible;
                }
                entity.Vis = Visibility.Collapsed;
                entity.BtnOk = Visibility.Hidden;
                entity.Btnclean = Visibility.Hidden;
                entity.Loginout = Visibility.Hidden;
                ClientService.EQPInfo = entity;
                entity.AuotoProcess = false;

                InitializeNATS();
                //测试登录
                //System.Windows.Application.Current.Dispatcher.Invoke(new Action(delegate
                //{
                //    Controller.ShowWindow(new LoginViewModel());
                //}));              
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(ex.ToString());
            }
        }

        public static void InitializeNATS()
        {
            try
            {
                XfwContext.InitializationXfw();
                // XfwContext.RegisterHeaderParser(XfwUtils.ParseHeader);
                XfwContext.StartXfw();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void TerminateNATS()
        {
            XfwContext.TerminateXfw();
        }
        static App()
        {
            DispatcherHelper.Initialize();
        }

        private static void InitKVMInfo(IConfiguration config)
        {
            var ip = config.GetSection("KVMIP").Get<string>();
            var port = config.GetSection("KVMPort").Get<int>();
            var userName = config.GetSection("KVMUserName").Get<string>();
            var password = config.GetSection("KVMPassword").Get<string>();
            var waitFor = config.GetSection("KVMWaitFor").Get<int>();
            var left = config.GetSection("KVMLeft").Get<int>();
            var top = config.GetSection("KVMLeft").Get<int>();
            ClientService.KvmInfo.KVMIP = ip;
            ClientService.KvmInfo.KVMPort = port;
            ClientService.KvmInfo.KVMUserName = userName;
            ClientService.KvmInfo.KVMPassword = password;
            ClientService.KvmInfo.KVMWaitFor = waitFor;
            ClientService.KvmInfo.KVMLeft = left;
            ClientService.KvmInfo.KVMTop = top;
        }
        /// <summary>
        /// 获取EAP.json中的文件信息
        /// </summary>
        private void ReadJson()
        {
            try
            {
                StreamReader sr = new StreamReader(System.IO.Directory.GetCurrentDirectory() + "\\Configuration\\EAP.json", System.Text.Encoding.Default);
                String line;
                string jsonobj = "";
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.Contains("//"))
                    {
                        continue;
                    }
                    jsonobj = jsonobj + line.ToString();
                }
                XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(jsonobj), XmlDictionaryReaderQuotas.Max);
                XmlDocument XmlDoc = new XmlDocument();
                XmlDoc.Load(reader);

                string Name = XmlDoc.SelectSingleNode("//Name").InnerText;
                Dict.Current.EAPName = Name;
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(ex.ToString());
            }
        }
    }
}
